<template>
  <div>
    <a-collapse :default-active-key="[1, 2, 3, 4, 5]" :bordered="false">
      <a-collapse-item header="公告内容" :key="1">
        <div class="chooseBox">
          <p class="title">滚动速度</p>
          <div class="radioBox" style="padding: 0px">
            <a-input type="text" v-model="currentTemp.step" placeholder="请输入滚动速度" />
          </div>
        </div>
        <div class="chooseBox">
          <p class="title">公告标题</p>
          <div class="radioBox" style="padding: 0px">
            <a-input type="text" v-model="currentTemp.noticeText" placeholder="请输入公告标题" />
          </div>
        </div>
        <div class="chooseBox">
          <p class="title">公告内容</p>
          <Toolbar :editor="editorRef" :default-config="toolbarConfig" />
          <Editor
            v-model="currentTemp.context"
            :default-config="editorConfig"
            class="editor_custom"
            style="height: 332px; overflow-y: hidden"
            @on-created="handleCreated"
            @on-change="handleChange"
            @on-destroyed="handleDestroyed"
            @on-focus="handleFocus"
            @on-blur="handleBlur"
            @custom-alert="customAlert"
            @custom-paste="customPaste"
          />
        </div>
      </a-collapse-item>
      <a-collapse-item header="间距(px)" :key="4">
        <div class="sliderBox">
          <p>上边距</p>
          <a-slider
            v-model="currentTemp.paddingTop"
            show-input
            style="width: 100%"
            :min="0"
            :max="100"
          />
        </div>
        <div class="sliderBox">
          <p>下边距</p>
          <a-slider
            v-model="currentTemp.paddingBottom"
            show-input
            style="width: 100%"
            :min="0"
            :max="100"
          />
        </div>
        <div class="sliderBox">
          <p>左右边距</p>
          <a-slider
            v-model="currentTemp.paddingTwice"
            show-input
            style="width: 100%"
            :min="0"
            :max="100"
          />
        </div>
      </a-collapse-item>
      <a-collapse-item header="圆角设置(px)" :key="3">
        <div class="sliderBox">
          <p>上圆角</p>
          <a-slider
            v-model="currentTemp.radiusNumTop"
            show-input
            style="width: 100%"
            :min="0"
            :max="100"
          />
        </div>
        <div class="sliderBox">
          <p>下圆角</p>
          <a-slider
            v-model="currentTemp.radiusNumBottom"
            show-input
            style="width: 100%"
            :min="0"
            :max="100"
          />
        </div>
      </a-collapse-item>
      <a-collapse-item header="背景设置" :key="2">
        <div class="chooseBox">
          <p class="title">展示类型</p>
          <div class="radioBox">
            <a-radio-group v-model="currentTemp.showType">
              <a-radio :value="1">
                <template #radio="{ checked }">
                  <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                    <div className="custom-radio-card-mask">
                      <div className="custom-radio-card-mask-dot"></div>
                    </div>
                    <div className="custom-radio-card-title">颜色</div>
                  </div>
                </template>
              </a-radio>
              <a-radio :value="2">
                <template #radio="{ checked }">
                  <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                    <div className="custom-radio-card-mask">
                      <div className="custom-radio-card-mask-dot"></div>
                    </div>
                    <div className="custom-radio-card-title">图片</div>
                  </div>
                </template>
              </a-radio>
            </a-radio-group>
          </div>
        </div>
        <div class="uploadBox" style="margin-bottom: 10px" v-if="currentTemp.showType == 2">
          <a-upload
            action="/app/file/upload"
            :show-file-list="false"
            @success="onSuccessBgImage($event)"
            @error="errorBgImage($event)"
            :image-preview="true"
          >
            <template #upload-button>
              <div class="arco-upload-list-picture custom-upload-avatar" v-if="currentTemp.bgImage">
                <img style="display: block; width: 80px; height: 80px" :src="currentTemp.bgImage" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                </div>
              </div>
              <!-- </div> -->
            </template>
          </a-upload>
        </div>

        <div class="sliderBox_color2" v-if="currentTemp.showType == 1">
          <p style="width: 100%; margin-bottom: 5px">填充颜色</p>
          <div
            style="
              width: 40px;
              height: 40px;
              cursor: pointer;
              border: 6px solid #f5f5f5;
              border-radius: 4px;
            "
            :style="{ backgroundColor: currentTemp.boxBg }"
            @click="changSketch3"
          ></div>

          <Sketch
            class="setColor"
            v-model="currentTemp.boxBg"
            :show="colorForm.showSketchBg"
            @changButton="changSketchBg"
          />

          <a-button type="text" style="margin-left: 12px" @click="currentTemp.boxBg = '#ffffff'"
            >重置</a-button
          >
        </div>
        <div class="sliderBox_color2">
          <p style="width: 100%; margin-bottom: 5px">字体颜色</p>

          <div
            style="
              width: 40px;
              height: 40px;
              cursor: pointer;
              border: 6px solid #f5f5f5;
              border-radius: 4px;
            "
            :style="{ backgroundColor: currentTemp.textColor }"
            @click="changSketch4"
          ></div>

          <Sketch
            class="setColor"
            v-model="currentTemp.textColor"
            :show="colorForm.showSketchFont"
            @changButton="changSketchFont"
          />

          <a-button type="text" style="margin-left: 12px" @click="currentTemp.textColor = '#000'"
            >重置</a-button
          >
        </div>
      </a-collapse-item>
    </a-collapse>
  </div>
</template>

<script setup lang="ts">
  import '@wangeditor/editor/dist/css/style.css'
  // import { usUploadStore } from '@/store/modules/upload'
  import { onBeforeUnmount, computed, ref, shallowRef, onMounted, watch } from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  // import * as http from '@/api/http'
  import { Message } from '@arco-design/web-vue'
  import { upLoadFiles } from '@/api/common'
  const emit = defineEmits(['change', 'update:modelValue'])
  import { Sketch } from '@ans1998/vue3-color'
  const props = defineProps({
    // 选中的当前组件参数
    config: {
      type: Object,
      default: () => {
        return {}
      },
    },
    modelValue: {
      type: String,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  })
  const typeLists = ref([
    { id: 1, name: '自定义' },
    { id: 2, name: '系统功能' },
  ])
  const colorForm = ref({ showSketchBg: false, showSketchFont: false })
  const currentTemp = computed(() => props.config)
  console.log(currentTemp.value)
  const clickdianType = (val: any) => {
    currentTemp.value.iconType = val
  }
  //背景图上传
  const onSuccessBgImage = (e: any) => {
    currentTemp.value.bgImage = e.response.data.path
    console.log(e)
  }
  const errorBgImage = (e: any) => {
    console.log(e)
    currentTemp.value.bgImage = e.response.data.path
  }
  const changSketchBg = (item: any) => {
    colorForm.value.showSketchBg = false
    console.log(item)
    if (item.isOk) {
      currentTemp.value.boxBg = item.activeColor
    } else {
      console.log('取消')
    }
  }
  const changSketchFont = (item: any) => {
    colorForm.value.showSketchFont = false
    console.log(item)
    if (item.isOk) {
      currentTemp.value.textColor = item.activeColor
    } else {
      console.log('取消')
    }
  }
  const changSketch3 = () => {
    colorForm.value.showSketchBg = true
  }
  const changSketch4 = () => {
    colorForm.value.showSketchFont = true
  }
  watch(
    () => currentTemp,
    (newVal, oldVal) => {
      emit('change', newVal.value)
    },
    { immediate: true, deep: true }
  )
  const toolbarConfig = {
    excludeKeys: ['group-video', 'insertImage', 'insertLink', 'emotion'], // 此处不需要的工具栏选项
  }
  const headerObj = ref({})
  const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {},
    hoverbarKeys: {
      image: {
        // 清空 image 元素的 hoverbar
        menuKeys: [],
      },
    },
  }

  // 上传图片
  editorConfig.MENU_CONF['uploadImage'] = {
    // 上传图片的接口地址
    server: upLoadFiles,
    // form-data fieldName ，默认值 'wangeditor-uploaded-image'
    fieldName: 'file',

    // 单个文件的最大体积限制，默认为 2M
    maxFileSize: 5 * 1024 * 1024, // 5M

    // 最多可上传几个文件，默认为 100
    maxNumberOfFiles: 20,

    // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
    allowedFileTypes: ['image/png,image/jpeg,image/jpg'],

    // 小于该值就插入 base64 格式（而不上传），默认为 0
    base64LimitSize: 0, // 5kb
    // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
    // meta: {
    //     token: 'xxx',
    //     otherKey: 'yyy'
    // },

    // 将 meta 拼接到 url 参数中，默认 false
    metaWithUrl: false,

    // 自定义增加 http  header
    headers: headerObj,

    // 跨域是否传递 cookie ，默认为 false
    withCredentials: true,

    // 超时时间，默认为 10 秒
    timeout: 5 * 1000, // 5 秒
    // 上传之前触发
    onBeforeUpload(file) {
      // file 选中的文件，格式如 { key: file }
      let fileObj = Object.values(file)[0].data
      const isJPG =
        fileObj.type == 'image/jpg' || fileObj.type == 'image/jpeg' || fileObj.type == 'image/png'
      if (!isJPG) {
        Message.error('图片只能是 JPG、GIF、PNG 格式!')
      }
      // 判断图片宽高
      // 定义 filereader对象

      // 判断图片大小
      let isLt = fileObj.size / 1024 / 1024 < 5 // 判断是否小于5M
      if (!isLt) {
        Message.error('图片大小不能超过5M! 请重新上传')
      }
      if (!isJPG) {
        return false
      } else if (!isLt) {
        return false
      } else {
        return file
      }
      // 可以 return
      // 1. return file 或者 new 一个 file ，接下来将上传
      // 2. return false ，不上传这个 file
    },
    // 上传进度的回调函数
    onProgress(progress) {
      // progress 是 0-100 的数字
      console.log('progress', progress)
    },
    // 单个文件上传成功之后
    onSuccess(file, res) {
      console.log(`${file.name} 上传成功`, res)
    },
    // 自定义插入图片
    customInsert(res, insertFn) {
      console.log(window.location.host)
      // res 即服务端的返回结果
      // 从 res 中找到 url alt href ，然后插图图片
      insertFn('http://' + window.location.host + res.data.path, '', '')
    },
    // 单个文件上传失败
    // onFailed(file, res) {
    //     console.log(`${file.name} 上传失败`, res)
    // },
    // 上传错误，或者触发 timeout 超时
    onError(file, err, res) {
      console.log(`${file.name} 上传出错`, err, res)
    },
  }
  // 上传视频
  editorConfig.MENU_CONF['uploadVideo'] = {
    // 上传视频接口地址
    // server: usUploadStore().uploadVideo,
    // form-data fieldName ，默认值 'wangeditor-uploaded-video'
    fieldName: 'file',

    // 单个文件的最大体积限制，默认为 10M
    maxFileSize: 5 * 1024 * 1024, // 5M

    // 最多可上传几个文件，默认为 5
    maxNumberOfFiles: 3,

    // 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
    allowedFileTypes: ['video/mp4'],

    // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
    // meta: {
    //     token: 'xxx',
    //     otherKey: 'yyy'
    // },

    // 将 meta 拼接到 url 参数中，默认 false
    metaWithUrl: false,

    // 自定义增加 http  header
    headers: headerObj,

    // 跨域是否传递 cookie ，默认为 false
    withCredentials: true,

    // 超时时间，默认为 30 秒
    timeout: 15 * 1000, // 15 秒

    // 视频不支持 base64 格式插入
    // 自定义插入视频
    customInsert(res, insertFn) {
      // res 即服务端的返回结果

      // 从 res 中找到 url ，然后插入视频
      insertFn(res.data.url)
    },
    // 上传之前触发
    onBeforeUpload(file) {
      // file 选中的文件，格式如 { key: file }
      return file

      // 可以 return
      // 1. return file 或者 new 一个 file ，接下来将上传
      // 2. return false ，不上传这个 file
    },
    // 上传进度的回调函数
    onProgress(progress) {
      // progress 是 0-100 的数字
      console.log('progress', progress)
    },
    // 单个文件上传成功之后
    onSuccess(file, res) {
      console.log(`${file.name} 上传成功`, res)
    },
    // 单个文件上传失败
    onFailed(file, res) {
      console.log(`${file.name} 上传失败`, res)
    },
    // 上传错误，或者触发 timeout 超时
    onError(file, err, res) {
      console.log(`${file.name} 上传出错`, err, res)
    },
  }
  // 组件销毁时，也及时销毁编辑器，重要！
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
  const editorRef = shallowRef()
  // 编辑器回调函数
  const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
    if (props.disabled) {
      editor.disable()
    } else {
      editor.enable()
    }
  }
  const handleChange = (editor) => {
    return editor
  }
  const handleDestroyed = (editor) => {
    // console.log('destroyed', editor)
    return editor
  }
  const handleFocus = (editor) => {
    //console.log('focus', editor)
    return editor
  }
  const handleBlur = (editor) => {
    //console.log('blur', editor)
    return editor
  }
  const customAlert = (info, type) => {
    alert(`【自定义提示】${type} - ${info}`)
  }
  const customPaste = (editor, event, callback) => {
    console.log('ClipboardEvent 粘贴事件对象', event)

    // 自定义插入内容
    // editor.insertText('xxx')

    // 返回值（注意，vue 事件的返回值，不能用 return）
    // callback(false) // 返回 false ，阻止默认粘贴行为
    callback(true) // 返回 true ，继续默认的粘贴行为
  }
</script>

<style scoped lang="less">
  .sliderBox_color2 {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 10px;
    position: relative;
    z-index: 10;
    overflow: visible;
    p {
      min-width: 50px;
      display: inline-block;
      margin-right: 12px;
    }
    .setColor {
      position: absolute;
      left: 120px;
      bottom: 30px;
      z-index: 1000000;
    }
  }
  .editor_custom {
    width: 100%;
  }
  .chooseBox {
    width: 100%;
    margin: 0px 0px 10px;
    display: flex;
    flex-wrap: wrap;
    .titles {
      width: 100%;
      display: block;
      margin-bottom: 5px;
    }
    .beizhu {
      font-size: 11px;
      color: #86909c;
      margin-top: 5px;
    }
    .radioBox {
      width: 100%;
      background-color: #f5f5f5;
      border-radius: 4px;
      height: 35px;
      display: flex;
      align-items: center;
      padding: 0px 10px;
      box-sizing: border-box;
    }
  }
  :deep(.w-e-text-container) {
    width: 100%;
    background-color: #f5f5f5;
  }
  :deep(.w-e-scroll) {
    overflow-y: hidden !important;
  }
  :deep(.w-e-text-container p) {
    margin: 8px 0px;
  }
  :deep(.w-e-text-container [data-slate-editor]) {
    overflow-y: auto !important;
    height: 100% !important;
  }
  :deep(.arco-upload-picture-card) {
    background: var(--color-bg-1);
  }
  :deep(.arco-collapse-item-content) {
    padding: 4px 0px;
    background: #fff;
    border: none;
    overflow: visible;
  }
  :deep(.arco-collapse-item-content-box) {
    padding: 0px 10px;
  }
  :deep(.arco-collapse-item-header) {
    border: none;
  }
  :deep(.arco-collapse-item) {
    border: none;
  }
  :deep(.arco-slider-track::before) {
    height: 4px;
  }
  :deep(.arco-slider-bar) {
    height: 4px;
  }
  :deep(.arco-collapse-item .arco-collapse-item-icon-hover) {
    position: absolute;
    top: 50%;
    left: 4px;
  }
  :deep(.arco-collapse-item-header-left) {
    padding-left: 24px;
  }
  .items {
    width: 100%;
    display: flex;
    align-items: center;
    margin-top: 12px;
    position: relative;
    .titles {
      min-width: 60px;
      margin-right: 20px;
      display: inline-block;
    }
    .setColor {
      position: absolute;
      left: 120px;
      bottom: 0px;
      z-index: 1000000;
    }
  }
  .pageBox {
    width: 100%;
    height: 36px;
    display: flex;
    cursor: pointer;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #f2f3f5;
    img {
      width: 30px;
    }
    .iconBox {
      width: 50%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .activeIcon {
      width: 50%;
      height: 100%;
      background-color: #f2f3f5;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>
